import breaDcrumb from '@/components/breadcrumb';
import set from '../components/set.vue';
import binding from '../components/binding.vue';
import { permissionsCompanyList } from "@/api/common.js";
import frequency from '../components/frequency.vue';
import LabelLife from '../components/labelLife.vue';
import {
  getListByTypeId
} from '@/api/common.js';
import {
  getFirmDetection,
  getNormByDetection,
  // saveNormByDetection
} from '@/api/basicConfig/CPYquality.js';
import { getDicType } from "@/api/common.js";
export default {
  components: {
    breaDcrumb,
    set,
    binding,
    frequency,
    LabelLife,
  },
  data() {
    return {
      code: '',
      companylist: [],
      contractTypelist: [{
        value: '验收标准',
        id: 0
      }, {
        value: '参数设置',
        id: 1
      },
      {
        value: '物料检测绑定',
        id: 2
      }, {
        value: '检验频率设置',
        id: 3
      }, {
        value: '标号寿命预警',
        id: 4
      }],
      currenindex: 0,
      leftList: [{
        text: '原物料',
        value: 1
      }, {
        text: '混凝土',
        value: 2
      }],

      rightList: [{
        text: '',
        value: 0
      }, {
        text: '质量要求',
        value: 1
      }, {
        text: '抽检指标',
        value: 2
      }],

      leftitemList: [],
      showrightitemList: [],
      rightitemList: [],
      tablenav: [],
      categoryList: [{
        name: '请优先选择对应的原物料或者强度等级'
      }],
      companyId: '',
      companyName: '',
      companyIdList: [],
      showleftIndex: 1,
      leftIndex: 1,
      leftitemId: '',
      showleftitemId: '',
      showrightIndex: 0,
      rightIndex: 0,
      loading: false,
      /**判断是否是交工数据*/
      bindingCategory: '',
      mappingProjectIdList: [],//交工资料绑定数据list
    };
  },
  async created() {
    this.companylist = await permissionsCompanyList()
    this.companyId = this.companylist[0].id
    this.companyName = this.companylist[0].name
  },
  watch: {
    /*监听左侧导航获取不同的左侧列表*/
    currenindex() {
      let _this = this
      if (_this.leftitemId == '') {
        return;
      }
      _this.gettightList()
    },
    leftIndex: {
      handler() {
        switch (this.leftIndex) {
          case 1: {
            getDicType({
              code: "MATname"
            }).then((res) => {
              this.leftitemList = res.data.items.map(res => {
                let obj = {
                  id: res.id,
                  name: res.itemName
                }
                return obj
              });
              this.leftitemId = ''
              this.showleftitemId = ''
              this.rightitemList = []
              this.showrightitemList = []
              this.tablenav = []
              this.showrightIndex = 0
              this.rightIndex = 0
              this.categoryList = [{
                name: '请优先选择对应的原物料或者强度等级'
              }]
            });
            return;
          }
          case 2: {
            getListByTypeId({
              typeId: 1
            }).then(res => {
              this.leftitemList = res.data;
              this.leftitemId = ''
              this.showleftitemId = ''
              this.rightitemList = []
              this.showrightitemList = []
              this.tablenav = []
              this.showrightIndex = 0
              this.rightIndex = 0
              this.categoryList = [{
                name: '请优先选择对应的原物料或者强度等级'
              }]
            });
            return;
          }
        }
      },
      deep: false, //是否深度监听，true为是，默认为false
      immediate: true //immediate表示在watch中首次绑定的时候，是否执
    },
    /*监听物料或者强度等级变化后获取右侧导航*/
    leftitemId() {
      let _this = this
      if (_this.leftitemId == '') {
        return;
      }
      _this.gettightList()
    },
    companyId() {
      if (this.leftitemId == '') {
        return;
      }
      this.gettightList()
    },
    /*右侧数据裱花刷新表单*/
    rightIndex() {
      this.getTable()
    },
  },
  methods: {
    gettightList() {
      let _this = this
      let data = new Object();
      data.type = _this.leftIndex;
      data.companyId = _this.companyId;
      if (_this.leftIndex == 1) {
        data.rawId = _this.leftitemId;
      } else {
        data.strengthGradeId = _this.leftitemId;
      }
      data.status = 1
      getFirmDetection(data).then(res => {
        if (res.data.length == 0) {
          _this.rightIndex = ''
          _this.showrightIndex = ''
          _this.categoryList = [{
            name: '暂未绑定检测类别'
          }]
        } else {
          _this.categoryList = res.data;
          _this.rightIndex = res.data[0].id
          _this.showrightIndex = res.data[0].id
          if (this.showleftIndex == 1 && res.data.findIndex((v) => v.type == 2) != -1) {
            _this.categoryList.push({ id: -1, name: '交工数据标准' })
          } else if (this.showleftIndex == 2 && res.data.findIndex((v) => v.type == 5) != -1) {
            _this.categoryList.push({ id: -1, name: '交工数据标准' })
          }
        }
      });
    },
    copy(list) {
      let str = JSON.stringify(list)
      return JSON.parse(str)
    },
    getTable() {
      this.loading = true
      let data = new Object();
      data.type = this.leftIndex;
      data.companyId = this.companyId;
      if (this.rightIndex == -1 && this.showleftIndex == 1) {
        data.id = this.categoryList.find((v) => v.type == 2).id
        data.checkStatus = 1//是否交工验收标准：1是；2否
      } else if (this.rightIndex == -1 && this.showleftIndex == 2) {
        data.id = this.categoryList.find((v) => v.type == 5).id
        data.checkStatus = 1//是否交工验收标准：1是；2否
      } else {
        data.id = this.rightIndex
        data.checkStatus = 2//是否交工验收标准：1是；2否
      }
      if (this.leftIndex == 1) {
        data.rawId = this.leftitemId;
      } else {
        data.strengthGradeId = this.leftitemId;
      }
      getNormByDetection(data).then(res => {
        this.tablenav = res.data.claim
        this.rightitemList = this.copy(res.data.list)
        this.showrightitemList = this.copy(res.data.list)
        if (this.rightIndex != '') {
          if (res.data.list.length == 0) {
            this.tablenav = []
            this.loading = false
            return
          }
          this.tablenav.unshift({
            name: "检测类别"
          })
          if (this.rightIndex == -1) {
            this.tablenav.push({ id: -1, name: '交工资料绑定数据' }, { id: -2, name: '是否交工数据' }, { id: -3, name: '下限值' }, { id: -4, name: '上限值' })
            for (let i = 0; i < this.rightitemList.length; i++) {//找交工资料绑定类别
              if (this.rightitemList[i][2]?.bindingCategory) {
                this.bindingCategory = this.rightitemList[i][2].bindingCategory
                this.bindingCategoryFun(true)
                break
              }
            }
            for (let i = 0; i < this.rightitemList.length; i++) {//找条件是否有数值是且/或
              this.rightitemList[i][4].symbol = this.rightitemList[i][1].symbol
              this.rightitemList[i][5].symbol = this.rightitemList[i][1].symbol
              this.rightitemList[i][4].symbolType = this.rightitemList[i][1].type
              this.rightitemList[i][5].symbolType = this.rightitemList[i][1].type
            }
          } else {
            this.code = ''
          }
          // this.showrightitemList = this.copy(this.rightitemList)
          if (this.rightitemList[0] && (Object.keys(this.rightitemList[0]).length - 4) > 1) {
            this.bindingCategory = this.rightitemList[0][String(Object.keys(this.rightitemList[0]).length - 4)].bindingCategory
          }
          if (this.bindingCategory) {
            this.bindingCategoryFun(true)
          }
        } else {
          this.showrightitemList = []
          this.rightitemList = []
        }
        this.loading = false
      })
    },
    addnbd() {
      if (this.rightIndex == -1 && !this.bindingCategory) {
        this.$message({
          message: "请选择交工资料绑定类别",
          type: "warning",
        });
        return
      }
      let _this = this
      /*构造数据对象*/
      function setdata(parameterSettingId, content, mappingProject, mappingProjectId, bindingCategory, checked, lowerLimitValue, upperLimitValue) {
        this.type = _this.leftIndex;
        this.companyId = _this.companyId;
        this.parameterSettingId = parameterSettingId;
        this.content = content;
        this.mappingProject = mappingProject;
        this.mappingProjectId = mappingProjectId;
        this.bindingCategory = bindingCategory;
        this.checked = checked;
        this.lowerLimitValue = lowerLimitValue;
        this.upperLimitValue = upperLimitValue;
        if (_this.leftIndex == 1) {
          this.rawId = _this.leftitemId;
        } else {
          this.strengthGradeId = _this.leftitemId;
        }
      }
      let arr = []
      try {
        console.log(JSON.parse(JSON.stringify(this.rightitemList)))
        this.rightitemList.forEach(res => {
          for (let key in res) {
            if (key !== '0') {
              arr.push(new setdata(res[key]?.id, res[key]?.name, res[key]?.mappingProject, res[key]?.mappingProjectId, this.bindingCategory, res[key]?.checked, res[key]?.lowerLimitValue, res[key]?.upperLimitValue))
              if (res[key]?.type == 3 && res[key]?.symbol.length !== 1) {
                if (this.judge(res[key]?.name)) {
                  throw Error();
                }
              }
            }
          }
        })
      } catch (e) {
        console.log(e)
        this.$message({
          message: '警告哦，数字为区间是请输入正确格式，如：10,20',
          type: 'warning'
        });
        return;
      }
      let name = this.leftitemList.find(res => (res.id == this.showleftitemId)).name
      let nameType = this.categoryList.find(res => (res.id == this.rightIndex)).name
      this.$router.push({ name: "sign_CPYquality", query: { tablenav: JSON.stringify(this.tablenav), rightitemList: JSON.stringify(this.rightitemList), arr: JSON.stringify(arr), companyName: this.companyName, type: 1, code: this.code, name: name, nameType: nameType, } });
      console.log(JSON.parse(JSON.stringify(this.rightitemList)))
      console.log(JSON.parse(JSON.stringify(this.tablenav)))
      console.log(JSON.parse(JSON.stringify(arr)))
      // debugger
      // saveNormByDetection(arr).then(() => {
      //   _this.getTable()
      // })

    },
    /**正则验证type=3就是数字含有且，或的格式 */
    judge(str) {
      let re = new RegExp(/^[0-9]+,[0-9]+$/)
      return !re.test(str)
    },
    change(hid, show, value) {
      let _this = this;
      console.log(this.showrightitemList);
      console.log(_this.rightitemList);
      if (JSON.stringify(_this.showrightitemList) !== JSON.stringify(_this.rightitemList)) {
        this.$confirm('请保存更改数据,否则数据将会丢失?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'bottom_all_two',
          confirmButtonClass: 'bottom_all',
          type: 'warning'
        })
          .then(() => {
            _this.addnbd();
            _this[show] = _this[hid]
          })
          .catch(() => {
            _this[show] = value;
            _this[hid] = value;
          });
        return;
      }
      _this[show] = value;
      _this[hid] = value;
    },
    choose(num) {
      this.currenindex = num
    },
    bindingCategoryFun(type) {
      if (!type) {
        this.rightitemList.forEach((v) => {
          if (v[Object.keys(v).length - 4]) {
            v[Object.keys(v).length - 4].bindingCategory = this.bindingCategory
            v[Object.keys(v).length - 4].mappingProjectId = ''
            v[Object.keys(v).length - 4].mappingProject = ''
          }
        })
      }
      this.code = ''
      if (this.bindingCategory == 1) {
        this.code = 'CommonConcreteMixDesignReport'
      } else if (this.bindingCategory == 2) {
        this.code = 'TestReportOfConcreteCubeCompressiveStrength'
      } else if (this.bindingCategory == 3) {
        this.code = 'TestReportOfConcreteImpermeability'
      } else if (this.bindingCategory == 4) {
        this.code = 'CementFactoryQualitTestReportAndCementTestReport'
      } else if (this.bindingCategory == 5) {
        this.code = 'SandTestReport'
      } else if (this.bindingCategory == 6) {
        this.code = 'AdmixtureProductQualityInspectionCertificate'
      } else if (this.bindingCategory == 7) {
        this.code = 'AdmixtureQualificationCertificate'
      } else if (this.bindingCategory == 8) {
        this.code = 'StoneTestReport'
      }
      this.mappingProjectIdList = []
      getDicType({ code: this.code }).then((res) => {
        this.mappingProjectIdList = res.data.items;
        console.log(JSON.parse(JSON.stringify(this.mappingProjectIdList)))
      });
    },
    mappingProjectIdFun(index, rowIndex, id) {
      let type = false
      this.rightitemList.forEach((v, k) => {
        if (v[2]?.mappingProjectId == id && rowIndex != k) {
          type = true
          this.$message({
            message: '不能选择交工资料绑定数据',
            type: 'warning'
          });
          this.rightitemList[rowIndex][2].mappingProjectId = ''
        }
      })
      if (type) {
        return
      }
      this.rightitemList[rowIndex][String(index)].mappingProject = this.mappingProjectIdList.find((v) => v.id == id).itemName
    },
    /**验证下限值是否填写正确 */
    lowerLimitUpperLimitFun(index, rowIndex, val, nameType) {
      console.log(index, rowIndex, val, nameType);
      console.log(this.rightitemList[rowIndex][String(1)].type);
      console.log(!this.judge(this.rightitemList[rowIndex][String(1)].name));
      if (this.rightitemList[rowIndex][String(1)].type == 3 && !this.judge(this.rightitemList[rowIndex][String(1)].name)) {
        if (this.checkOkNgFun(val, this.rightitemList[rowIndex][String(1)].symbol, this.rightitemList[rowIndex][String(1)].name) != 'OK') {
          if (nameType == 'lowerLimitValue') {
            this.rightitemList[rowIndex][String(index)].lowerLimitValue = ''
          } else {
            this.rightitemList[rowIndex][String(index)].upperLimitValue = ''
          }
          this.$message({
            message: '请输入满足' + this.rightitemList[rowIndex][String(1)].name + '的值',
            type: 'warning'
          });
        }
      }
    },

    /**验证OK还是NG */
    checkOkNgFun(val, technicalRequirements, section) {
      console.log(val, technicalRequirements, section);
      if (technicalRequirements == '≥') {
        if (Number(val) >= Number(section)) {
          return 'OK'
        } else {
          return 'NG'
        }
      } else if (technicalRequirements == '＞') {
        if (Number(val) > Number(section)) {
          return 'OK'
        } else {
          return 'NG'
        }
      } else if (technicalRequirements == '≤') {
        if (Number(val) <= Number(section)) {
          return 'OK'
        } else {
          return 'NG'
        }
      } else if (technicalRequirements == '＜') {
        if (Number(val) < Number(section)) {
          return 'OK'
        } else {
          return 'NG'
        }
      } else if (technicalRequirements == '=') {
        if (Number(val) == Number(section)) {
          return 'OK'
        } else {
          return 'NG'
        }
      } else if (technicalRequirements == '≤x,且x≤') {
        if (Number(val) >= Number(section.split(',')[0]) && Number(val) <= Number(section.split(',')[1])) {
          return 'OK'
        } else {
          return 'NG'
        }
      } else if (technicalRequirements == '<x,且x<') {
        if (Number(val) > Number(section.split(',')[0]) && Number(val) < Number(section.split(',')[1])) {
          return 'OK'
        } else {
          return 'NG'
        }
      } else if (technicalRequirements == '≤x,且x<') {
        if (Number(val) >= Number(section.split(',')[0]) && Number(val) < Number(section.split(',')[1])) {
          return 'OK'
        } else {
          return 'NG'
        }
      } else if (technicalRequirements == '<x,且x≤') {
        if (Number(val) > Number(section.split(',')[0]) && Number(val) <= Number(section.split(',')[1])) {
          return 'OK'
        } else {
          return 'NG'
        }
      } else if (technicalRequirements == 'x≤,或x≥') {
        if (Number(val) <= Number(section.split(',')[0]) || Number(val) >= Number(section.split(',')[1])) {
          return 'OK'
        } else {
          return 'NG'
        }
      } else if (technicalRequirements == 'x<,或x>') {
        if (Number(val) < Number(section.split(',')[0]) || Number(val) > Number(section.split(',')[1])) {
          return 'OK'
        } else {
          return 'NG'
        }
      } else if (technicalRequirements == '≤x,或x<') {
        if (Number(val) >= Number(section.split(',')[0]) || Number(val) < Number(section.split(',')[1])) {
          return 'OK'
        } else {
          return 'NG'
        }
      } else if (technicalRequirements == '<x,或x≤') {
        if (Number(val) > Number(section.split(',')[0]) || Number(val) <= Number(section.split(',')[1])) {
          return 'OK'
        } else {
          return 'NG'
        }
      }
    },
  }
};